package com.example.zkWebClient.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.data.Stat;
import org.springframework.stereotype.Service;

import com.example.zkWebClient.domain.ZNode;
import com.example.zkWebClient.service.NodeService;
import com.example.zkWebClient.utils.ZooKeeperClientUtils;

@Service
public class NodeServiceImpl implements NodeService {

	@Override
	public List<String> findChildNodes(String path) {
		List<String> list = new ArrayList<>();
		try {
			list = ZooKeeperClientUtils.getInstance().getChildren(path, null, null);
		} catch (KeeperException | InterruptedException e) {
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public String addNode(ZNode node) throws KeeperException, InterruptedException {
		CreateMode createMode = CreateMode.fromFlag(node.getType());
		String pathCreated = ZooKeeperClientUtils.getInstance().create(
				node.getPath(), 
				node.getData().getBytes(), 
				Ids.OPEN_ACL_UNSAFE,
				createMode);
		return pathCreated;
	}

	@Override
	public void delNode(String path) throws InterruptedException, KeeperException {
		ZooKeeperClientUtils.getInstance().delete(path, -1);
	}

	@Override
	public void updateNode(ZNode node) throws KeeperException, InterruptedException {
		ZooKeeperClientUtils.getInstance().setData(node.getPath(), node.getData().getBytes(), -1);
	}

	@Override
	public int getCountOfChildNodes(String path) {
		int count = 0;
		try {
			Stat stat = ZooKeeperClientUtils.getInstance().exists(path, Boolean.FALSE);
			if (stat != null) {
				count = stat.getNumChildren();
			}
		} catch (KeeperException | InterruptedException e) {
			e.printStackTrace();
		}
		return count;
	}

	@Override
	public ZNode getNode(String path) {
		ZNode node = null;
		try {
			Stat stat = new Stat();
			byte[] bytes = ZooKeeperClientUtils.getInstance().getData(path, Boolean.FALSE, stat);
			node = new ZNode();
			node.setPath(path);
			node.setData(new String(bytes));
			node.setStat(stat);
		} catch (KeeperException | InterruptedException e) {
			e.printStackTrace();
		}
		return node;
	}

}
